<script setup>
import { useRouter } from 'vue-router';
import { ref, onUnmounted } from 'vue';
import message from '../components/message.vue'
import axios from 'axios'
const modal = ref(null)
const router = useRouter();
const goback = () => {
    router.go(-1);
}
let oldpassword = ref()
let newpassword = ref()
let newpassword2 = ref()
let timer = null

const update = () => {
    if (oldpassword.value === '' || newpassword.value === '' || newpassword2.value === '') {
        modal.value.show({
            code: 0,
            msg: '请输入完整信息'
        })

    } else if (newpassword.value !== newpassword2.value) {
        modal.value.show({
            code: 0,
            msg: '两次密码不一样'
        })
    } else {
        console.log(oldpassword.value);
        axios({
            method: 'post',
            url: 'http://localhost:8080/student/checkpassword',
            params: {
                oldpassword: oldpassword.value
            }, withCredentials: true
        }).then(async function (response) {
            if (response.data.code == 1) {
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/student/update',
                    params: {
                        password: newpassword.value,
                    },
                    withCredentials: true
                }).then(function (response) {
                    modal.value.show(response.data)
                    timer = setTimeout(() => (
                        router.push('/index')
                    ), 1000);
                })
            }
        })
    }
}

onUnmounted(() => {
    if (timer) {
        clearTimeout(timer);
    }
});
</script>
<template>
    <div class="updatestudentpassworld">
        <div class="title">
            <button type="button" @click="goback">
                < 返回</button>
                    <p>修改密码</p>
        </div>
        <div class="main">
            <p>请输入旧密码：</p>
            <input type="password" id="oldpassword" placeholder="请输入旧密码" v-model="oldpassword">
            <p>请输入新密码：</p>
            <input type="password" id="newpassword" placeholder="请输入新密码" v-model="newpassword">
            <p>请确认新密码：</p>
            <input type="password" id="newpassword2" placeholder="请确认新密码" v-model="newpassword2">
            <button type="button" @click="update">提交</button>
        </div>
    </div>
    <message ref="modal" />
</template>

<style>
.updatestudentpassworld {
    width: 780px;
    height: 98%;
    background-color: #fdf9eb;
    margin: 5px;
}

.title {
    height: 30px;
    width: 100%;
    background-color: #dedede;
    display: flex;
}

.title p {
    line-height: 30px;
    margin-left: 20px;
    color: #585858;
}

.title button {
    display: block;
    margin-left: 5px;
}
</style>